<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		Mr.Tung Dev Team
 */
/*
 * 1.load libray
 * 2.call function classname::method
*/
class clsString
{
	public function __construct(){
		$this->CI=& get_instance();	
	}
	//convert tieng viet khong dau
	public static function kodau($str)
	{
		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
		$str = preg_replace("/( )/", '-', $str);
		$str = preg_replace("/(\'|\"|`|&|,|\.|\?)/", '', $str);
		$str = preg_replace("/(---|--)/", '-', $str);
		
		$pattern = '/([^a-z0-9\-\._])/i';
		$str = preg_replace($pattern, '', $str);
			
		$str = strtolower($str);
		return $str;
	}
	/* number:The number being formatted.
	** decimals:Sets the number of decimal points.
	** dec_point:Sets the separator for the decimal point.
	** thousands_sep:Sets the thousands separator*/
	
	public static function numberformart($num,$decimals=2,$dec_point=',',$thousands_sep=' ')
	{
		return number_format($num,$decimals,$dec_point,$thousands_sep);
	}
	/* insert zero to string
	** $number:input number
	** $n:times zero */
	public static function number_pad($number,$n) {
		return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
	}
	//allow tag html
	//allow tag \n
	public static function htm_tag_1($text,$tag='\n')
	{
		return strip_tags($text,$tag);	
	}
	//allow tag <em>,<u>,<br>,\n
	public static function htm_tag_2($text)
	{
		$tag='<em>,<u>,<br>,\n';
		return strip_tags($text,$tag);	
	}
	//allow tag <a>,<img>,<em>,\n
	public static function htm_tag_3($text)
	{
		$tag='<a>,<img>,<em>,\n';
		return strip_tags($text,$n);	
	}
	/*allow <p>, <font>, <span>, <a>, <img>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <strong>, <b>, <em>, <i>, <u>, <br>, <sub>, <sup>,<video>, <iframe>, <object>, <param>, <embed>, <ul>, <ol>, <li>, <table>, <tbody>, <theade>, <tfoot>, <tr>, <th>, <td>*/
	public static function htm_tag_4($text)
	{
		$tag='<p>, <font>, <span>, <a>, <img>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <strong>, <b>, <em>, <i>, <u>, <br>, <sub>, <sup>,<video>, <iframe>, <object>, <param>, <embed>, <ul>, <ol>, <li>, <table>, <tbody>, <theade>, <tfoot>, <tr>, <th>, <td>';
		return strip_tags($text,$tag);	
	}
	/*** return year/mounth/day
	*	$day:string
	*/
	public static function datemysql($day=''){
		return strftime("%Y-%m-%d", strtotime($day));
	}
	// return ip of user
	public static function getUserIP()
	{
		$client  = @$_SERVER['HTTP_CLIENT_IP'];//ip from share internet
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];//ip is pass from proxy
		$remote  = $_SERVER['REMOTE_ADDR'];
	
		if(filter_var($client, FILTER_VALIDATE_IP)){
			$ip = $client;
		}elseif(filter_var($forward, FILTER_VALIDATE_IP)){
			$ip = $forward;
		}else{
			$ip = $remote;
		}
		return $ip;
	}
	/* 
	@param:string
	return lat and lng;
	*/
	public static function getLatLng($address){
		try{
			$address = urlencode($address);
			$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false');
	
			$output= json_decode($geocode);
	
			$lat = $output->results[0]->geometry->location->lat;
			$lng = $output->results[0]->geometry->location->lng;
			if(is_numeric($lat) && is_numeric($lng)){
				return array("lat" => $lat, "lng" => $lng);
			}
		}
		catch(Exception $e){            
			return false;
		}
	}
	
	/* function check domain
	*	@param string
	*	return value domain
	*/
	function checkdomain($domain)
	{
		$rex='/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix';
		if(preg_match_all($rex,$domain,$out)){
			return $out[0][0];
		}	
	}
	
	
	/**
	*	@package: Alsasuri
	*	@subpackage: Ultilities
	*	@Author: Alsasuri Dev Team
	*	@Date: 1/20/2014
	*/
	/**
	*	@Description: Convert dd/mm/yyyy date format to yyyy-mm-dd system date format
	*	@param: string
	*	@return: string
	*/
	public static function convert_to_system_date($str_date)
	{
		return implode('-', array_reverse(explode('/',$str_date)) );	
	}
	/**
	*	@Description: Convert a dimension array to string
	*	@param: array
	*	@param: string separator to join array, default empty
	*	@return: string
	*/
	public static function convert_array_to_string($arr_array, $separator=false)
	{
		if( ! is_array( $arr_array ) ) {
			return '';
		}
		if( $separator ) {
			return implode($separator, $arr_array);
		}
		return implode('', $arr_array);	
	}

	/**
	*	@Description: Valid date input
	*	@param: string	
	*	@param: string
	*	@return: bool
	*/
	public static function validate_date($str_date , $separator='-')
	{
		$pos = strpos($str_date, $separator);
		if($pos === false )  {
			return false;
		}
		$info = explode($separator, $str_date);
		if( count($info) != 3 ) {
			return false;
		}				
		if(! checkdate($info[2],$info[1], $info[0]) ) {
			return false;
		}
		return true;
	}
	/**
	*	@Description: Valid Url and check domain still live
	*	@param: string
	*	@return: bool
	*/
	public static function validate_url($str_url )
	{	
		/*$pattern = '/^(http|https):\/\/[a-zA-Z0-9]{2,}\.[a-z]{2,3}/';	*/		
		$pattern = '/^(?:[;\/?:@&=+$,]|(?:[^\W_]|[-_.!~*\()\[\] ])|(?:%[\da-fA-F]{2}))*$/';		
		if( preg_match( $pattern, $str_url,$matches ) == 1 ) {
			if(checkdnsrr($matches[1])) {
				return true;
			}
		   return false;
		}
		return false;
	}
	/**
	*	@description: Get user ip address
	*	@param: none
	*	@return: string
	*/
	public static function get_ipaddress() {
		return $_SERVER['REMOTE_ADDR'];
	}
	/**
	*	@description: Get Longitude and Latitude from ip address
	*	@param: string
	*	@return: array if false return array empty
	*/
	public static function get_longitude_latitude($address) {
		$service_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$address."&sensor=false";
		$content = file_get_contents($service_url);
		$info = json_decode($content);
		$ret = array();
		if($info->status === 'OK') {
			//print_r($info->results[0]);
			$lat_long = $info->results[0]->geometry->location;
			$ret['lat'] = $lat_long->lat;
			$ret['long'] = $lat_long->lng;			
		}		
		return $ret;		
	}
	/*
	*	@description: use to upload file
	*	@param: string - name of file input 
	*	@param: array()
	*	$return : string file path if success else empty string ''
	*/
	public static function upload($file, $options = array()) {
		$_options = array(
			'path' =>'./uploads/',
			'size' => 10485760,//10MB
			'type'=> array('image/png','image/jpg'),
		);
		// merge config
		if(count($options) > 0 ) {
			array_merge($_options, $options);
		}
		// is upload
		if( !isset($_FILES[$file]) ) {
			return '';
		}
		// check error
		if( $_FILES[$file]['error'] > 0 ) {
			return '';
		}
		// check file type
		if( ! in_array($_FILES[$file]['type'] , $_options['type']) ) {
			return '';
		}				
		$dir = $_options['path'].date('Y/m/d/');		
		if(!file_exists($dir) AND is_writable($_options['path'])) {
			mkdir($dir, 0755, true);
		}
		$info = pathinfo($_FILES[$file]['name']);
		$new_path = $dir. DIRECTORY_SEPARATOR .$info['filename']. '_'.time().'.'.$info['extension'];
		if( ! move_uploaded_file($_FILES[$file]['tmp_name'],$new_path) ) {
			return '';
		}		
		return $new_path;
	}	
	
	/**
	*	@description: create thumnail image
	*	@param: string path to file
	*	@param: int percet to resize image
	*	@param: int image quality
	*	@return: array if false return array empty
	*/
	public static function create_thumbnail($file, $percent = 25 , $quality = 75) {
		if( ! file_exists($file)) {
			return;
		}
		$thumb = new Thumbnail($file,0,0,$percent,$quality);
		$info = pathinfo($file);
		$thumb->save($info['dirname'].DIRECTORY_SEPARATOR .time().'_thumb_'.$info['basename']);
	}
	
	/**
	*	@description: send email
	*	@param: string email address
	*	@param: string message to send	
	*	@param: string path to file attach
	*	@return: bool
	*/
	
	public static function send_email($to, $message , $attach = false) {		
		$CI->config->load('mail');
		$mail = new Email;
		// debug
		$mail->SMTPDebug  = (bool)$CI->config->item('DEBUG');		
		$mail->isSMTP();                                    
		$mail->Host = $CI->config->item('HOST');
		$mail->Port = $CI->config->item('PORT');
		$mail->SMTPAuth = $CI->config->item('AUTH');  
		$mail->Username = $CI->config->item('USERNAME');
		$mail->Password = $CI->config->item('PASSWORD');
		$mail->SMTPSecure = $CI->config->item('SMTP_SECURE');;

		$mail->From = $CI->config->item('FROM');
		$mail->FromName = $CI->config->item('FROM_NAME');
		$mail->addAddress($to, 'Customer');
		$mail->addReplyTo($CI->config->item('FROM'), 'Information');		

		$mail->WordWrap = $CI->config->item('WORD_WRAP');             
		if( $attach ) {
			if(file_exists($attach) ) {
				$mail->addAttachment($attach);			
			}
		}
		$mail->isHTML($CI->config->item('IS_HTML'));                              

		$mail->Subject = $CI->config->item('SUBJECT');
		$mail->Body    = $message;
		//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

		if(!$mail->send()) {
		   return false;
		}
		return true;
	}
}

